package cn.kent.server.handler;

import cn.kent.message.GroupChatRequestMessage;
import cn.kent.message.GroupChatResponseMessage;
import cn.kent.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;

/**
 * 群聊功能 处理器
 */
@ChannelHandler.Sharable
public class GroupChatRequestMessageHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage msg) throws Exception {
        List<Channel> channels = GroupSessionFactory.getGroupSession()
                .getMembersChannel(msg.getGroupName());

        // 判断本人是否在群聊中,不在则不能往群聊发消息
        if (channels.contains(ctx.channel())) {
        for (Channel channel : channels) {
            GroupChatResponseMessage response = new GroupChatResponseMessage(true, "发送成功");
            response.setFrom(msg.getFrom());
            response.setContent(msg.getContent());
            channel.writeAndFlush(response);
        }}else{
            ctx.channel().writeAndFlush(new GroupChatResponseMessage(false, "您不在该群聊中,不可以往该群聊中发消息"));
        }
    }
}
